package mws;


import java.util.concurrent.atomic.AtomicInteger;


/**
 * Hello world!
 *
 */
public class ReadWriteLock {

//读写锁 读共享 写和读互斥

    public AtomicInteger atomicInteger = new AtomicInteger(0);

    public Object writeLock = new Object();

    public Thread threadHold = null;

    public volatile int writeEnter = 0;

    public AtomicInteger readEnter = new AtomicInteger(0);

    public ReadLock getReadLock(){
        return new ReadLock();
    }
    public WriteLock getWriteLock(){
        return new WriteLock();
    }

    class ReadLock   {
        public void lock() {
          while (atomicInteger.get() % 2 == 1);
            readEnter.incrementAndGet();
        }
        public void unlock(){
            readEnter.decrementAndGet();
        }

    }

    class WriteLock {



        public void lock() {
            synchronized (writeLock){
                if(atomicInteger.get() % 2 == 0){
                    writeEnter = 1;
                    atomicInteger.incrementAndGet();
                    threadHold = Thread.currentThread();
                }
            }
            while (readEnter.get() != 0){};
            if(Thread.currentThread().equals(threadHold)){
                writeEnter++;
            }else {
                while (atomicInteger.get() % 2 == 1 );
            }
        }


        public void unlock() {
            if(atomicInteger.get() % 2 == 1 && threadHold.equals(Thread.currentThread())){
                   if(writeEnter == 1){
                       atomicInteger.incrementAndGet();
                   }else {
                       writeEnter--;
                   }
            }
        }

    }

}